/***************************************************************************
 *   Copyright (C) 2007 by gaojian   *
 *   gaojian2008cnn@vip.sina.com  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "dictionary.h"
#include "settings.h"

#include <qstring.h>
#include <qregexp.h>
#include <qbuffer.h>
#include <qtextcodec.h>

#include <kurl.h>
#include <klocale.h>
#include <kio/jobclasses.h>
bool Dictionary::netcomOrTelecom=true ;
Dictionary::Dictionary(QObject *parent, const char *name)
	: QObject(parent, name)
{	
	targetWord = "";
}


Dictionary::~Dictionary()
{
}


/*!
    \fn Dictionary::search(const QString& text)
 */
void Dictionary::search(const QString& text)
{
	QString word=text.simplifyWhiteSpace();
    //判断输入的第一个字符是否是26个字母
	if( -1==word.left(1).find( QRegExp("[a-z,A-Z]"), 0) ) //如果等于－1那么 就不是字母，作为数字和汉字处理
    {
	    qDebug("是数子或汉子");
	    searchCNWord(text);
    }
    else //作为单词处理
    {
	    qDebug("是字母");
	    searchENWord(text);
	    targetWord = text;
    }

}


/*!
    \fn Dictionary::searchCNWord(QString &word)
 */
void Dictionary::searchCNWord(const QString &word)
{
	buffer = new QBuffer;
	buffer->open(IO_WriteOnly);	
	KIO::TransferJob *  job = KIO::get(KURL(i18n("http://dict.yodao.com/search?q="+word)).url(), false, false);
	QObject::connect( job, SIGNAL(data(KIO::Job *, const QByteArray &)), this, SLOT(slotBufferData(KIO::Job *, const QByteArray &)));
	QObject::connect(job, SIGNAL(result(KIO::Job *)), this,SLOT(slotCHResult(KIO::Job *)));
}


/*!
    \fn Dictionary::searchENWord(const QString &word)
 */
void Dictionary::searchENWord(const QString &word)
{
	buffer = new QBuffer;
	buffer->open(IO_WriteOnly);
	QString url;
	if (kdictsettings.b_netcomOrTelecom)//为true表示为网通
	{
		url="http://bj.dict.cn/search/?q="+word;
	}else{//否则为电信
		url="http://dict.cn/search/?q="+word;
	}
	KIO::TransferJob *  job = KIO::get(KURL(i18n(url)).url(), false, false);
	QObject::connect( job, SIGNAL(data(KIO::Job *, const QByteArray &)), this, SLOT(slotBufferData(KIO::Job *, const QByteArray &)));
	QObject::connect(job, SIGNAL(result(KIO::Job *)), this,SLOT(slotENResult(KIO::Job *)));
}


/*!
    \fn Dictionary::slotData(KIO::Job *job, const QByteArray &data)
 */
void Dictionary::slotBufferData(KIO::Job *job, const QByteArray &data)
{
	buffer->writeBlock(data.data(), data.size());
}


/*!
    \fn Dictionary::slotCHResult(KIO::Job *job)
 */
void Dictionary::slotCHResult(KIO::Job *job)
{
	QByteArray arraydata= buffer->buffer();//根据buffer字节大小初始化
	arraydata.detach();//抓取数据
	delete buffer;//这是个好习惯
	buffer = NULL;
	//if ( job->error() )//判断kio：job是否有错误
	//job->showErrorDialog(this->parent());//由于dictionary类不是继承自qwidget所以无法满足参数要求
	job->kill(true);
	job = NULL;
	QString str = QString(arraydata);
	
	if ( -1 != str.find( QString("<!--eng chn result start-->"), 0 ) )//find返回-1证明返回的页面不正确或者说没找到结果
	{
		int i = str.find( QString("<!--eng chn result start-->"), 0 );
		int j = str.find( QString("<!--eng chn result end-->"), 0 );
		str = str.mid( i, j-i );//截取i和j之间的数据
		if (int k=str.find("</BR>"))//把"近义词或词组"前的图片去掉
		{
			str.insert(k,"</td></tr> <tr><td>");
			QString img("<IMG SRC=\"images/pointd.gif\" WIDTH=\"5\" HEIGHT=\"5\" BORDER=\"0\" ALT=\"\" align=absmiddle><font class=pgrayd>");
			int m = str.find( img, 0 );
			str=str.remove(m,img.length());
			emit searchResult(str);//把找到的结果发送出去
			
		}
	}
	else{
		emit searchError("对不起，没有找到解释");
	}
	
	
}


/*!
    \fn Dictionary::slotENResult(KIO::Job *job)
 */
void Dictionary::slotENResult(KIO::Job *job)
{
	QByteArray arraydata= buffer->buffer();
	arraydata.detach();
	delete buffer;
	buffer = NULL;
	//if ( job->error() )
	//job->showErrorDialog( this   );
	job->kill(true);
	job = NULL;
	QString str = QString(arraydata).simplifyWhiteSpace();
	QTextCodec *codec = QTextCodec::codecForName("gb2312"); // 把2312编码转换为Unicode编码
	str = codec->toUnicode( str );
	QTextCodec *codec1 = QTextCodec::codecForName("utf8"); // 把Unicode编码转换为utf8编码
	str = codec1->fromUnicode( str);
	if(-1!=str.find("No similar words found!"))//网页中出现这句证明什么也没找到
	{
		emit searchError("对不起，没有找到解释");
		return;
	}
	if( -1!= str.findRev("<table border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">"))
	{
		
		QString mid;
		int i = str.findRev("<table border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">");
		if(-1!=str.find("您要查找的是不是:"))//如果出现这句说明存在模糊查询
		{
			int r=str.findRev("</td><td height=492 width=1>");
			str = str.mid( i, r-i );//截取表格部分
			emit searchResult(str);//把找到的结果发送出去
			return;
		}
		int j = str.find("</table>",i);
		j+=8;
		str = str.mid( i, j-i );//截取表格部分
		
		int k = str.find("<script");
		if(-1!=k)
		{
			int m = str.find("&nbsp;<a href");
			mid=str.mid(k,m-k);//截取发音部分
			str=str.remove(k,mid.length());//删除发音部分
			str=str.insert(k,getFlashHtml(targetWord));//插入爱词霸的发音flash
		}
		int n = str.find("<a href='ja");
		if(-1!=n)
		{
		int p = str.find("<br><br> <big>");
		mid=str.mid(n,p-n);//截取加入生词本部分
		str=str.remove(n,mid.length());//删除加入生词本部分
		str=str.insert(n,getWordBookHtml(targetWord));
		}
		emit searchResult(str);//把找到的结果发送出去
	}else{
		emit searchError("对不起，没有找到解释");
	}
}

/*!
    \fn Dictionary::getFlashHtml(const QString& word)
 */
QString Dictionary::getFlashHtml(const QString& word)
{
	QString t = word.left( 1 );
	QString html;
	html+="<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0\" width=\"20\" height=\"20\">";
	html+="<param name=\"wmode\" value=\"transparent\">";
	html+="<param name=\"movie\" value=\"http://cb.kingsoft.com/resource/a/en/"+t+"/"+word+".swf\" />";
	html+="<param name=\"quality\" value=\"high\" />";
	html+="</OBJECT>";
	return html;
}

/*!
    \fn Dictionary::getWordBookHtml(const QString& word)
 */
QString Dictionary::getWordBookHtml(const QString& word)
{
	QString html="<a href='http://bbs.dict.cn/vocabulary.php?mini=2&word="+word;
	html+="' title='添加到我的生词本'><img src=http://www.iciba.com/image/v2/icon4.gif border=0 align=absmiddle></a>";
	return html;
}
#include "dictionary.moc"